<?php
// Test of R0910CMS 
// created by zyn
// time : 20100124
// edit by wc

include_once "DbStruct.php";
//include "../src/Redrock0910CMS.php";
class DbTest extends WebTestCase {
	private $db=array();
	private $_db=null;
    function testAccess() {
        $this->get(R_Data::get('cfg','http_root') .'src/R/Db/Manage.php');
        $this->assertTitle('');
        $this->assertPattern('/Access Denied!/');
    }
    function setUp() {
        $cfg = R_Data::get('cfg');
        $this->db['host'] = $cfg['dbHost'];
        $this->db['user'] = $cfg['dbUser'];
        $this->db['pwd']  = $cfg['dbPwd'];
        $this->db['name'] = $cfg['dbName'];
        //$this->_db  = new R_Db_Db($this->db['host'],$this->db['user'], 
        //    $this->db['pwd'], $this->db['name']);
        $this->_db  = getInstance('R_Db_Db',$this->db['host'],$this->db['user'], 
            $this->db['pwd'], $this->db['name']);
        // as it will be run 6 times or i will use setInstance to setUp it
        // althrough I use the full param all the times,it make sence only in first time
        $this->_db->setNames('gbk');

    }
    function tearDown() {
    }

	function testDb(){}
	
    function testDbConstruct() {
        $db = new R_Db_Db($this->db['host'],$this->db['user'], 
            $this->db['pwd'], $this->db['name']);

        // test setnames
        $db -> setNames();//default gbk
        $db -> setNames('utf8');//
        try{ $db -> setNames('abc'); }
        catch(PDOException $e){	
			
            $this->assertEqual($e->getMessage(),"SQLSTATE[42000]: Syntax error or access violation: 1115 Unknown character set: 'abc'");
            $this->assertEqual($e->getCode(),42000);
        }

        $this->assertEqual( 'PDO', get_class($db -> getConn()) );


        
    }
    function testRow() {
        // pre for assert
        $eq = 'assertEqual';

        // create the table
        $tb = new TablePeople($this->_db);
        try {
            $tb->create(); 
        } catch(PDOException $e) {
            $tb->drop();
            $tb->create(); 
        }
        
        //test create table sql
        $this->assertEqual($s = $tb->getCreateSQL(),join("\n",array(
            "CREATE TABLE `people` (",
                "`id` INT(11) unsigned NOT NULL  AUTO_INCREMENT ,",
                "`name` VARCHAR(10)  NULL   COMMENT 'User Name',",
                "`age` INT(10)  NULL   ,",
                " PRIMARY KEY (`id`)",
            ") ENGINE=MyISAM DEFAULT CHARSET=gbk;"
            ) // end of array
            )
        );

        // test drop table sql
        $this->assertEqual($tb->getDropSQL()
            ,"DROP TABLE IF EXISTS `people`;");

        // test setup a row
        $tb = new TablePeople($this->_db);
        $a = array('id' => intval('0'), 'name' => 'wc',
                   'age'=> intval('20') );
        $tb->FromArray($a);
        $this->assertEqual($tb->col['id']->getValue(), 0);
        $this->assertEqual($tb->col['name']->getValue(), 'wc');
        $this->assertEqual($tb->col['age']->getValue(), 20);


 		// test row insert
        $tb->insert();
		$col['name'] = "ZYN";
		$col['age']  = 20 ;       
        $tb2 = new TablePeople($this->_db, $col);
        $id2 = $tb2 -> insert();
        $this->$eq(2,$id2);

        // test row select
        $tb3 = new TablePeople($this->_db);
        $tb3 ->set('id', intval($id2)); // set the primary
        $tb3 ->select();
        $this->$eq('ZYN',$tb3->get('name'));

        // test row update
        $tb3 ->set('name','wc2') ->update();
        // test row update result
        $tb3t = new TablePeople($this->_db, array('id' => intval($id2)));
        $tb3t -> select();
        $this->$eq('wc2' ,$tb3t->get('name'));

        // test update with param
        $tb4 = new TablePeople($this->_db);
        $tb4->select(array('id'),array('name'=>'wc2'));
        $this->$eq($tb4->get('id'),$id2);

        // test row delete
        $tb2->set('id' ,intval($id2));
        $this->$eq(1, // affected row
            $tb2->delete());

        // drop table if exists
        $tb = new TablePeople($this->_db);
        $tb->drop();
		
        // test add slashes
    }

    function testDbFunctions() {
        $eq = 'assertEqual';
        // create the table
        $tb = new TablePeople($this->_db);
        try {
            $tb->create(); 
        } catch(PDOException $e) {
            $tb->drop();
            $tb->create(); 
        }

        // test db select
        $sql = "SELECT * FROM ".$tb->tableName;
        $sql_ret = $this->_db->query($sql);
        $this->$eq(array(),$sql_ret->fetchAll());

        // test db insert
        $id = $this->_db->insert(array('table' =>$tb->tableName,
            'values' => array('name'=>'wc', 'age' => 12 )
            ) //end of array
        );
        $this->$eq(1,$id);

        $id = $this->_db->insert(array('table' =>$tb->tableName,
            'values' => array('name'=>'wc', 'age' => 12 )
            ) //end of array
        );
        $this->$eq(2,$id);

        // test db select
        $sql = "SELECT * FROM ".$tb->tableName;
        $sql_ret = $this->_db->query($sql);
        $this->$eq(2,count($sql_ret->fetchAll()));
        
        $selRet = $this->_db->select(array( 'table' => $tb->tableName, 
                'what' => '*',           
                'where'=> '1=1',
            ) // end of array
        );
        $this->$eq(2,count($selRet->fetchAll()));

        $selRet = $this->_db->select(array( 'table' => $tb->tableName, 
                'what' => '*',           
                'where'=> '1=1',
                'limit'=> array(0,1),
            ) // end of array
        );
        $this->$eq(1,count($selRet->fetchAll()));

        // test db update
        $updRet = $this->_db->update( array('table'=>$tb->tableName, 
            'set'    =>  array('name'=>'ZYN',), 
            'where'  =>  array('id'=>$id-1,),
            ) 
        );
        $this->$eq(1,$updRet); // update success
        // test db update restult
        $selRet = $this->_db->select(array( 'table' => $tb->tableName, 
                'what' => '*',           
                'where'=> array('id'=>$id-1),
            ) // end of array
        );
        $arrRet = $selRet->fetchAll();
        $this->$eq('ZYN',$arrRet[0]['name']);
        
        // test db delete
        $delRet = $this->_db->delete(array( 'table'=>$tb->tableName, 
            'where' => array('id' => $id-1),
        ));
        $this->$eq(1, // affected row
            $delRet);

        $delRet = $this->_db->delete(array( 'table'=>$tb->tableName, 
            'where' => "`id` = '$id'",
        ));
        $this->$eq(1, // affected row
            $delRet);

        // drop table if exists
        $tb = new TablePeople($this->_db);
        $tb->drop();
    }

    function testDbManage() {
        $eq = 'assertEqual';
		
		try{
			R_Db_Manage::get();
		}catch(R_Exception_ParamWrong $e) {
			$this->$eq($e->getMessage(),'No default Db Connection!');
		}

		$lk = &R_Db_Manage::get('goodlink',$this->db['host'],$this->db['user'], 
            $this->db['pwd'], $this->db['name']);
		$lkcl = &$lk;
		// no name means last conn
		$lk2 = &R_Db_Manage::get();
		$this->assertTrue($lk===$lk2);
		//pr(phpversion());
		// a no argument instance
		$lk3 = R_Db_Manage::get('aNewConn');
		
		$this->assertTrue($lk != $lk3);

		return;
    }

    function testRowList() {
        // pre for assert
        $eq = 'assertEqual';

        // create the table
        $tb = new TablePeople($this->_db);
        try {
            $tb->create(); 
        } catch(PDOException $e) {
            $tb->drop();
            $tb->create(); 
        }
        $this->_db->insert(array('table' =>$tb->tableName,
            'values' => array('name'=>'wc', 'age' => 12 )
            ) //end of array
        );
        $this->_db->insert(array('table' =>$tb->tableName,
            'values' => array('name'=>'wc', 'age' => 12 )
            ) //end of array
        );

        // test for the filling a list
        $r = new R_Db_RowList(array(
            'rowName' => 'TablePeople',
            'where'   => '1=1',
            'db'      => $this->_db,
            )
        );
        $this->$eq($r->fill(),array ( 
            array ( 'id' => "1", 'name' => "wc",'age' => "12" ), array ( 'id' => "2",'name' => "wc",'age' => "12" ) ) );

        // test for a object list
        $r->fill();
        $oa = $r->getObjectList();
        $this->$eq($oa[0]->col['id']->getValue() , "1" );

        // test for a object list with order
            // DESC
        $r->order = array('id'=> 'DESC');
        $r->fill();
        $oa = $r->getObjectList();
        $this->$eq($oa[0]->col['id']->getValue() , "2" );
            // ASC
        $r->order = array('id'=> 'ASC');
        $r->fill();
        $oa = $r->getObjectList();
        $this->$eq($oa[0]->col['id']->getValue() , "1" );


        for($i=0;$i<18;$i++) {
            $this->_db->insert(array('table' =>$tb->tableName,
                'values' => array('name'=>'wc', 'age' => 12 )
                ) //end of array
            );
        }
        $r->order = array('id'=> 'ASC');
        $arr_ret = $r->fillWithPager(new R_Db_Pager(3,3));
        $this->$eq($arr_ret[0]['id'], '7');

        $arr_ret = $r->fillWithPager(new R_Db_Pager(4,10));
        $this->$eq($arr_ret[0]['id'], '11');

        // drop table if exists
        $tb = new TablePeople($this->_db);
        $tb->drop();
    }
}

